package com.jingyanzi.channel.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.jingyanzi.channel.service.IChannelService;
import com.jingyanzi.channel.service.IChannelTypeService;
import com.jingyanzi.channel.service.IChannelWindowService;
import com.jingyanzi.channel.service.IContactsService;

public class ChannelFactory {

	private static AtomicBoolean isInit = new AtomicBoolean(false);
	
	private static ApplicationContext context = null;
	
	private static AtomicBoolean isTest = new AtomicBoolean(false);
	
	public static void initCofing() {
		Properties properties = new Properties();
		InputStream in = ChannelFactory.class.getClassLoader().getResourceAsStream("application.properties");
		try {
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String value = properties.getProperty("run.test");
		if(value.equals("on")) {
			isTest.set(true);
		}
		if (!isInit.get()) {
			if(isTest.get()) {
				context = new FileSystemXmlApplicationContext(
						"classpath:channel-test-application.xml");
				System.out.println("init test application.xml");
			} else {
				context = new FileSystemXmlApplicationContext(
						"classpath:channel-application.xml");
				System.out.println("init application.xml");
			}
			isInit.set(true);
		}	
	}
	
	public static IChannelService getChannelService() {
		initCofing();
		IChannelService channelService = (IChannelService) context.getBean("channelservice");
		return channelService;
	}
	
	public static IChannelTypeService getChannelTypeService() {
		initCofing();
		IChannelTypeService channelTypeService = (IChannelTypeService) context.getBean("channeltypeservice");
		return channelTypeService;
	}
	
	public static IChannelWindowService getChannelWindowService() {
		initCofing();
		IChannelWindowService channelWindowService = (IChannelWindowService) context.getBean("channelwindowservice");
		return channelWindowService;
	}
	
	public static IContactsService getContactsService() {
		initCofing();
		IContactsService contactsService = (IContactsService) context.getBean("contactsservice");
		return contactsService;
	}
	
}
